import 'dart:ui';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lang/app_locales.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_lifecycle_base/base_state_widget.dart';
import 'package:wallet_home/module_config.dart';
import 'package:wallet_home/page/theme/colors.dart';
import 'package:wallet_home/tools/common.dart';
import 'package:wallet_home/tools/theme_utils.dart';

class LangPage extends BaseStatefulWidget {
  @override
  _LangPageState createState() {
    return _LangPageState();
  }
}

class _LangPageState extends BaseWidgetState<LangPage> {
  final List<String> _list = [
    "${WXLang.$t("home_language_chinese", package: ModuleConfig.moduleName)}",
    "${WXLang.$t("home_language_english", package: ModuleConfig.moduleName)}",
    "${WXLang.$t("home_language_system", package: ModuleConfig.moduleName)}"
  ];
  int position = 0;
  Locale _switchLocale;

  @override
  void initState() {
    super.initState();
    String themeType = SpUtil.getString(Constant.langModel);
    switch (themeType) {
      case "zh":
        position = 0;
        break;
      case "en":
        position = 1;
        break;
      default:
        position = 2;
        break;
    }
  }

  /// 切换语言后需要重新初始化
  void _initData() {
    _list[0] =
        "${WXLang.$t("home_language_chinese", package: ModuleConfig.moduleName)}";
    _list[1] =
        "${WXLang.$t("home_language_english", package: ModuleConfig.moduleName)}";
    _list[2] =
        "${WXLang.$t("home_language_system", package: ModuleConfig.moduleName)}";
  }


  @override
  void didAppear() {
    super.didAppear();
  }

  @override
  void disappear() {
    super.disappear();
  }

  @override
  Widget build(BuildContext context) {
    _initData();
    print("语言切换页面刷新了====>$position");
    return Scaffold(
        appBar: AppBar(
          //  backgroundColor: position == 1 ? Colors.black : Colors.white,
          title: Text(
            "${WXLang.$t("home_language_select", package: ModuleConfig.moduleName)}",
          ),
          centerTitle: true,
          elevation: 0.0,
          automaticallyImplyLeading: true,
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color:
              ThemeUtils.isDark(context) ? Colours.dark_bg_color : Colors.white,
          child: ListView.separated(
            separatorBuilder: (_, index) => Divider(),
            itemCount: _list.length,
            itemBuilder: (_, index) {
              return InkWell(
                onTap: () {
                  if (position == index) return;

                  position = index;

                  if (_languageSwitchRefresh()) {
                    WXLocales.onLocaleChanged(_switchLocale);
                  }

                  setState(() {});
                },
                child: Container(
                  alignment: Alignment.centerLeft,
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  height: 40.0,
                  child: Row(
                    children: <Widget>[
                      Expanded(child: Text(_list[index])),
                      Opacity(
                        opacity: position == index ? 1 : 0,
                        child: Icon(
                          Icons.done,
                          color: ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colours.app_main,
                              darkColor: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ));
  }

  bool _languageSwitchRefresh() {
    bool isRefresh = true;

    String landMode;

    /// 切换前的语言，如果是和默认系统语言一致则不处理
    String lastLang = SpUtil.getString(Constant.langModel);

    if(position == 0) {
      landMode = "zh";
      _switchLocale = Locale("zh", "CH");
      WXLocales.setFollowSystem(false);
    } else if(position == 1) {
      landMode = "en";
      _switchLocale = Locale("en", "US");
      WXLocales.setFollowSystem(false) ;
    } else { /// 如果是系统跟随，当前语言即为系统语言时不做切换
      landMode = "system";
      WXLocales.setFollowSystem(true);

      if (lastLang == WXLocales.systemLocale?.languageCode) {
        isRefresh = false;
      } else {
        _switchLocale = WXLocales.systemLocale;
      }
    }

    if (position == 0 || position == 1) {
      /// 如果上一次是跟随系统也有可能和切换后的相等，若相等则不重读语言库，如当前系统时英语，再切到英语应该不刷新
      if (lastLang == "system" &&
          WXLocales.systemLocale?.languageCode == landMode) {
        isRefresh = false;
      }
    }

    SpUtil.putString(Constant.langModel, landMode);

    return isRefresh;
  }
}
